package com.ruoyi.projectAch.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.projectAch.domain.*;
import com.ruoyi.projectAch.domain.Result.SchoolNameAndLevel;
import com.ruoyi.projectAch.mapper.AchievementInfoMapper;
import com.ruoyi.projectAch.mapper.GrantingUnitMapper;
import com.ruoyi.projectAch.mapper.SchoolNameMapper;
import com.ruoyi.projectAch.service.IAchievementInfoService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;

/**
 * 成果信息Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-07
 */
@Service
public class AchievementInfoServiceImpl implements IAchievementInfoService {
    @Autowired
    private AchievementInfoMapper achievementInfoMapper;

    @Autowired
    private GrantingUnitMapper grantingUnitMapper;

    @Autowired
    private SchoolNameMapper schoolNameMapper;


    /**
     * 查询成果信息
     *
     * @param id 成果信息主键
     * @return 成果信息
     */
    @Override
    public AchievementInfo selectAchievementInfoById(Long id) {
        return achievementInfoMapper.selectAchievementInfoById(id);
    }

    /**
     * 查询成果信息列表
     *
     * @param achievementInfo 成果信息
     * @return 成果信息
     */
    @Override
    public List<AchievementInfo> selectAchievementInfoList(AchievementInfo achievementInfo) {
        return achievementInfoMapper.selectAchievementInfoList(achievementInfo);
    }

    /**
     * 新增成果信息
     *
     * @param achievementInfo 成果信息
     * @return 结果
     */
    @Override
    public int insertAchievementInfo(AchievementInfo achievementInfo) {
        return achievementInfoMapper.insertAchievementInfo(achievementInfo);
    }

    /**
     * 修改成果信息
     *
     * @param achievementInfo 成果信息
     * @return 结果
     */
    @Override
    public int updateAchievementInfo(AchievementInfo achievementInfo) {
        return achievementInfoMapper.updateAchievementInfo(achievementInfo);
    }

    /**
     * 批量删除成果信息
     *
     * @param ids 需要删除的成果信息主键
     * @return 结果
     */
    @Override
    public int deleteAchievementInfoByIds(Long[] ids) {
        return achievementInfoMapper.deleteAchievementInfoByIds(ids);
    }

    /**
     * 删除成果信息信息
     *
     * @param id 成果信息主键
     * @return 结果
     */
    @Override
    public int deleteAchievementInfoById(Long id) {
        return achievementInfoMapper.deleteAchievementInfoById(id);
    }

    @Override
    public List<SchoolName> querySchoolName() {
        return schoolNameMapper.selectSchoolNameList(null);
    }

    @Override
    public List<GrantingUnit> queryGrantingUnit() {
        return grantingUnitMapper.selectGrantingUnitList(null);
    }

    @Override
    public String importUser(List<AchievementInfo> achievementInfoList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(achievementInfoList) || achievementInfoList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (AchievementInfo info : achievementInfoList) {
            try {
                info.setCreateBy(operName);
                //判断是否支持更新
                if (isUpdateSupport){
                    //执行更新操作
                    achievementInfoMapper.updateAchievementInfo(info);
                }else {
                    //执行插入操作
                    achievementInfoMapper.insertAchievementInfo(info);
                }
                successNum++;
            } catch (Exception e) {
                failureNum++;
                e.printStackTrace();
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确。");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，");
        }
        return successMsg.toString();
    }

    @Override
    public List<AchievementInfo> selectSchoolName(AchievementInfo achievementInfo) {
        List<AchievementInfo>  list = achievementInfoMapper.selectSchoolNameByDateAndMark(
                achievementInfo.getStartTime(),achievementInfo.getEndTime());
        return list;
    }

    @Override
    public List selectLevel(AchievementInfo achievementInfo) {
       List list = achievementInfoMapper.selectLevel(
               achievementInfo.getStartTime(),achievementInfo.getEndTime()
       );
        return list;
    }

    public Data getAchievementsData(String startTime, String endTime) {
        List<Achievement> achievements = achievementInfoMapper.selectAchievements(startTime, endTime);
        Set<String> schoolNames = new HashSet<>();
        Set<String> achievementNames = new HashSet<>();

        // 提取学校名和成果名
        for (Achievement achievement : achievements) {
            schoolNames.add(achievement.getSchoolName());
            achievementNames.add(achievement.getAchievementName());
        }

        // 构建 yaxdata 部分
        List<School> schools = new ArrayList<>();
        for (String name : schoolNames) {
            schools.add(new School(name));
        }

        // 构建 seriesarray 部分
        List<AchievementSeries> seriesList = new ArrayList<>();
        for (String achievementName : achievementNames) {
            AchievementSeries series = new AchievementSeries(achievementName, new ArrayList<>());
            for (String schoolName : schoolNames) {
                int count = 0;
                for (Achievement achievement : achievements) {
                    if (achievement.getSchoolName().equals(schoolName) && achievement.getAchievementName().equals(achievementName)) {
                        count = achievement.getCount();
                        break;
                    }
                }
                series.getNumbers().add(new AchievementCount(achievementName, count));
            }
            seriesList.add(series);
        }

        // 组装并返回数据
        Data data = new Data();
        data.setYaxdata(schools);
        data.setSeriesarray(seriesList);
        return data;
    }



    @Override
    public List<Map<String, Object>> selectTotal(
            @Param("schoolName") String schoolName,
            @Param("startDate") String startTime,
            @Param("endDate") String endTime
    ) {
        List<Map<String, Object>> list = achievementInfoMapper.selectTotal(schoolName, startTime, endTime);
        return list;
    }


}
